#include <stdio.h>
#include <stdbool.h>
#include <string.h>

#include "FreeRTOS.h"
#include "task.h"

#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "hardware/spi.h"
#include "pico.h"
#include "hardware/irq.h"
#include "breathing_led.h"
#include "led.h"  // 添加LED任务头文件
#include "ds3231_rtc.h"  // 添加DS3231 RTC头文件
#include "ht1621b.h"  // 添加HT1621B LCD头文件
#include "segment_codes.h" // 添加段码控制头文件
#include "LOG.h"
#include "hardware/uart.h"
#include "board.h"
#include "buzzer.h"
#include "alarm.h"
#include "rotary_encoder.h"
#include "countdown.h"
#include "key_handler.h"

// 主任务配置
#define MAIN_TASK_NAME "MainControl"
#define MAIN_TASK_STACK (configMINIMAL_STACK_SIZE + 512)
#define MAIN_TASK_PRIO (tskIDLE_PRIORITY + 1)

rtc_time_t current_time;
tick_time_t down_time;
// 闹钟数组
alarm_t alarms[2]; // 支持两个闹钟

uint32_t uCountMs = 0;
bool RTC_1S_INT = false;
bool led_breathing_mode = false; // 初始为呼吸模式

key_state_t KEY_WAIT = KEY_RELEASED;
key_state_t KEY_ALARM1 = KEY_RELEASED;
key_state_t KEY_ALARM2 = KEY_RELEASED;
key_state_t KEY_CONFIRM = KEY_RELEASED;
key_state_t KEY_A = KEY_RELEASED;
key_state_t KEY_B = KEY_RELEASED;
key_state_t KEY_T = KEY_RELEASED;

uint8_t systemWorkMode = SYSTEM_RTC_MODE;
SYSTEM_WAKEUP_EVT systemWakeupEvent;
SYSTEM_WORK_MODE systemWorkMode;
SYSTEM_STATE systemstate;

static bool colon_visible = true;
static uint8_t beep_count = 0;
// 倒计时状态变量
static rotary_event_t rotary_evt = ROTARY_EVENT_NONE;
static uint32_t tick_count = 0;

// RTC页面相关变量
static RTC_PAGE_TYPE rtc_current_page = RTC_PAGE_TIME; // 当前显示的页面
static bool rtc_page_changed = false;                  // 页面是否发生变化

// 任务句柄
static TaskHandle_t main_task_handle = NULL;

static void ds3231_int_handle(void);
static void countdown_test(void);

static void countdown_finished_callback(void)
{
    // 播放10次提示音
    if (beep_count < COUNT_DOWN_NUM)
    {
            // 开始播放提示音
            buzzer_beep(500); // 500ms鸣响
            beep_count++;
            LOG_INFO("Countdown finished, playing beep %d/10", beep_count);
    }
    else
    {
        LOG_INFO("Countdown finished, 10 beeps played, stopping countdown");
        // 可选：重置倒计时时间
        // countdown_reset();
        // 停止倒计时
        countdown_stop();
        // 10次提示音播放完毕，重置状态
        beep_count = 0;
        systemWorkMode = SYSTEM_RTC_MODE;
    }
}

static uint8_t setting_step = 0; // 0: hours, 1: minutes, 2: seconds

static void key_long_press_lcd(tick_time_t *time)
{
    // 根据当前工作模式确定使用哪个时间结构
    bool is_countdown_mode = (systemWorkMode == SYSTEM_COUNTDOWN_MODE);
    
    // 处理旋转编码器事件
    switch (rotary_evt)
    {
    case ROTARY_EVENT_CLOCKWISE:
        switch (setting_step)
        {
        case 0: // 设置分钟
            if (is_countdown_mode) {
                time->countdown_time.minutes++;
                if (time->countdown_time.minutes > 59)
                    time->countdown_time.minutes = 0;
            } else {
                time->alarm_time.hours++;
                if (time->alarm_time.hours > 23)
                    time->alarm_time.hours = 0;
            }
            break;
        case 1: // 设置秒
            if (is_countdown_mode) {
                time->countdown_time.seconds++;
                if (time->countdown_time.seconds > 59)
                    time->countdown_time.seconds = 0;
            } else {
                time->alarm_time.minutes++;
                if (time->alarm_time.minutes > 59)
                    time->alarm_time.minutes = 0;
            }
            break;
        case 2: // 设置毫秒（倒计时模式）或小时（闹钟模式）
            if (is_countdown_mode) {
                time->countdown_time.milliseconds = 0;
            } else {
                time->alarm_time.seconds++;
                if (time->alarm_time.seconds > 59)
                    time->alarm_time.seconds = 0;
            }
            break;
        }
        break;

    case ROTARY_EVENT_COUNTERCLOCKWISE:
        switch (setting_step)
        {
        case 0: // 设置分钟
            if (is_countdown_mode) {
                if (time->countdown_time.minutes > 0)
                    time->countdown_time.minutes--;
                else
                    time->countdown_time.minutes = 59;
            } else {
                if (time->alarm_time.hours > 0)
                    time->alarm_time.hours--;
                else
                    time->alarm_time.hours = 23;
            }
            break;
        case 1: // 设置秒
            if (is_countdown_mode) {
                if (time->countdown_time.seconds > 0)
                    time->countdown_time.seconds--;
                else
                    time->countdown_time.seconds = 59;
            } else {
                if (time->alarm_time.minutes > 0)
                    time->alarm_time.minutes--;
                else
                    time->alarm_time.minutes = 59;
            }
            break;
        case 2: // 设置毫秒（倒计时模式）或小时（闹钟模式）
            if (is_countdown_mode) {
                    time->countdown_time.milliseconds = 99;
            } else {
                if (time->alarm_time.seconds > 0)
                    time->alarm_time.seconds--;
                else
                    time->alarm_time.seconds = 59;
            }
            break;
        }
        break;

    case ROTARY_EVENT_BUTTON_PRESSED:
        setting_step++;
        if (setting_step > 2)
        {
            setting_step = 0;
        }
        LOG_INFO("setting_step: %d", setting_step);
        break;
    case ROTARY_EVENT_BUTTON_LONG_PRESSED:
        LOG_INFO("systemWorkMode: %d", systemWorkMode);
        // 长按旋转编码器按钮，作为确认键使用
        if (systemWorkMode == SYSTEM_COUNTDOWN_MODE)
        {
            if (time->status != TICK_STATUS_RUNNING)
            {
                countdown_start();
                LOG_INFO("Countdown started via rotary encoder long press");
            }
        }
        else if (systemWorkMode == SYSTEM_ALARM1_MODE)
        {
            // 确认闹钟1设置
            systemWorkMode = SYSTEM_RTC_MODE;
            LOG_INFO("Alarm 1 settings confirmed via rotary encoder long press");
        }
        else if (systemWorkMode == SYSTEM_ALARM2_MODE)
        {
            // 确认闹钟2设置
            systemWorkMode = SYSTEM_RTC_MODE;
            LOG_INFO("Alarm 2 settings confirmed via rotary encoder long press");
        }
        break;
    default:
        break;
    }

    // 显示当前设置的时间（闪烁对应部分）
    ht1621b_clear_buffer();
    
    // 闹钟模式：显示小时、分钟、秒
    segment_display_RTC_time_blink(time->alarm_time.hours, 
                                    time->alarm_time.minutes, 
                                    time->alarm_time.seconds,
                                    setting_step == 0, setting_step == 1, setting_step == 2);
}

// 按键事件处理回调函数
static void key_event_callback(key_type_t key_type, key_event_t event)
{
    switch (key_type)
    {
    case KEY_TYPE_WAIT: // 倒计时按键 (KEY1)
        switch (event)
        {
        case KEY_EVENT_PRESSED:
            // 短按同时触发蜂鸣器
            systemWorkMode = SYSTEM_COUNTDOWN_MODE;

            buzzer_beep_short();
            countdown_setting();
            setting_step++;
            if (setting_step > 2)
            {
                setting_step = 0;
            }     

            LOG_INFO("Countdown key pressed");
            break;

        case KEY_EVENT_LONG_PRESSED:
            countdown_reset();
            LOG_INFO("Countdown key long pressed");
            buzzer_beep(500); // 500ms鸣响
            break;

        case KEY_EVENT_RELEASED:
            LOG_INFO("Countdown key released");
        default:
            // 正常运行，无特殊操作
            break;
        }
        break;

    case KEY_TYPE_ALARM1: // 闹钟1按键 (KEY4)
        switch (event)
        {
        case KEY_EVENT_PRESSED:
            systemWorkMode = SYSTEM_ALARM1_MODE;
            // 短按切换闹钟1状态
            if (alarm_is_enabled(1))
            {
                alarm_enable(1, false);
                LOG_INFO("Alarm 1 disabled");
            }
            else
            {
                alarm_enable(1, true);
                LOG_INFO("Alarm 1 enabled");
            }
            // 短按同时触发蜂鸣器
            buzzer_beep_short();
            break;

        case KEY_EVENT_LONG_PRESSED:
            // 长按设置闹钟1时间
            buzzer_beep(500); // 500ms鸣响
            LOG_INFO("Long press on Alarm 1 - Set time");
            break;

        case KEY_EVENT_RELEASED:
        default:
            // 正常运行，无特殊操作
            break;
        }
        break;

    case KEY_TYPE_ALARM2: // 闹钟2按键 (KEY2)
        switch (event)
        {
        case KEY_EVENT_PRESSED:
            systemWorkMode = SYSTEM_ALARM2_MODE;
            // 短按切换闹钟2状态
            if (alarm_is_enabled(2))
            {
                alarm_enable(2, false);
                LOG_INFO("Alarm 2 disabled");
            }
            else
            {
                alarm_enable(2, true);
                LOG_INFO("Alarm 2 enabled");
            }
            // 短按同时触发蜂鸣器
            buzzer_beep_short();
            break;

        case KEY_EVENT_LONG_PRESSED:
            // 长按设置闹钟2时间
            buzzer_beep(500); // 500ms鸣响
            LOG_INFO("Long press on Alarm 2 - Set time");
            break;

        case KEY_EVENT_RELEASED:
        default:
            // 正常运行，无特殊操作
            break;
        }
        break;

    case KEY_TYPE_HOME: // HOME按键 (KEY3)
        switch (event)
        {
        case KEY_EVENT_PRESSED:
            // 短按HOME键，在时钟界面和其他界面之间切换
            if (systemWorkMode == SYSTEM_RTC_MODE) {
                // 如果当前在时钟界面，则切换到倒计时模式
                systemWorkMode = SYSTEM_COUNTDOWN_MODE;
            } else {
                // 如果当前不在时钟界面，则切换回时钟界面
                systemWorkMode = SYSTEM_RTC_MODE;
            }
            buzzer_beep_short();
            LOG_INFO("HOME key pressed - Switching mode to %d", systemWorkMode);
            break;

        case KEY_EVENT_LONG_PRESSED:
            // 长按HOME键可以用于其他功能，比如重置所有设置
            LOG_INFO("HOME key long pressed");
            buzzer_beep(500); // 500ms鸣响
            break;

        case KEY_EVENT_RELEASED:
        default:
            // 正常运行，无特殊操作
            break;
        }
        break;

    default:
        break;
    }
}


// 按键初始化
static void key_init(void)
{
    // 初始化所有按键GPIO为输入模式
    gpio_init(KEY1_PIN);
    gpio_set_dir(KEY1_PIN, GPIO_IN);
    gpio_pull_up(KEY1_PIN); // 启用上拉电阻
    
    gpio_init(KEY2_PIN);
    gpio_set_dir(KEY2_PIN, GPIO_IN);
    gpio_pull_up(KEY2_PIN); // 启用上拉电阻
    
    gpio_init(KEY3_PIN);
    gpio_set_dir(KEY3_PIN, GPIO_IN);
    gpio_pull_up(KEY3_PIN); // 启用上拉电阻
    
    gpio_init(KEY4_PIN);
    gpio_set_dir(KEY4_PIN, GPIO_IN);
    gpio_pull_up(KEY4_PIN); // 启用上拉电阻
    
    LOG_INFO("Keys initialized: KEY1=%d, KEY2=%d, KEY3=%d, KEY4=%d", KEY1_PIN, KEY2_PIN, KEY3_PIN, KEY4_PIN);
}

// 主任务处理函数
static void main_task_handler(void *pvParameters)
{
    // 初始化LED GPIO
    led_gpio_init();
    key_handler_init();     // 初始化按键处理模块
    rotary_encoder_init();  // 初始化旋转编码器
    countdown_init();       // 初始化倒计时模块，传入外部变量
    countdown_register_callback(countdown_finished_callback); // 注册倒计时完成回调函数
    key_handler_register_callback(key_event_callback);        // 注册按键事件回调函数
    stdio_init_all();
    LOG_INFO("stdio initialized successfully");

    memset(&alarms, 0, sizeof(alarms));

    // 先全亮显示一次
    ht1621b_display_all_segments();
    LOG_INFO("HT1621B - All segments lit");

    ds3231_callback_register(ds3231_int_handle);

    // 切换到固定亮度模式
    breathing_led_set_constant_mode(BREATHING_MAX_BRIGHTNESS / 5);

    /*     // 初始化蜂鸣器
        if (!buzzer_init()) {
            LOG_ERROR("Failed to initialize buzzer");
            // 使用LED进行错误提示
            LedHandleRegister(SYSTEM_DEVICE_INIT_ERROR);
            return 1;
        } */

    // 初始化呼吸灯模块
    if (!breathing_led_init())
    {
        LOG_ERROR("Failed to initialize breathing LED module");
        // 使用LED进行错误提示
        LedHandleRegister(SYSTEM_DEVICE_INIT_ERROR);
    }

    // 初始化DS3231 RTC模块
    if (!ds3231_rtc_init())
    {
        LOG_ERROR("Failed to initialize DS3231 RTC module");
        // 使用LED进行错误提示
        LedHandleRegister(SYSTEM_DEVICE_INIT_ERROR);
    }

    // 初始化HT1621B LCD模块
    if (!ht1621b_init())
    {
        LOG_ERROR("Failed to initialize HT1621B LCD module");
        // 使用LED进行错误提示
        LedHandleRegister(SYSTEM_DEVICE_INIT_ERROR);
    }

    // 初始化闹钟模块
    alarm_init();

    LOG_INFO("Starting FreeRTOS scheduler...");
    LOG_INFO("System running with only two tasks: HT1621B LCD and Main Control");
    LOG_INFO("Breathing LED on GPIO%d - 1s cycle (smooth)", BREATHING_PWM_GPIO);
    LOG_INFO("DS3231 RTC running on I2C0 (SDA=%d, SCL=%d)", DS3231_SDA_PIN, DS3231_SCL_PIN);

    LOG_INFO("Main control task started");
    LOG_INFO("=== FreeRTOS System Starting ===");
    while (1)
    {
        tick_count+=MAIN_TASK_DELAY_MS;
        if (systemWakeupEvent & SYSTEM_WAKEUP_EVT_CLOCK)
        {
            systemWakeupEvent &= ~SYSTEM_WAKEUP_EVT_CLOCK;
            colon_visible = !colon_visible;
            switch (systemWorkMode)
                {
                case SYSTEM_RTC_MODE:
                    if (RTC_1S_INT)
                    {
                        RTC_1S_INT = false;
                        if (down_time.status == TICK_STATUS_RUNNING)
                        {
                            countdown_param_update();
                        }
                        // 清除所有段
                        ht1621b_clear_buffer();

                        // 根据当前页面显示不同内容
                        switch (rtc_current_page)
                        {
                        case RTC_PAGE_TIME:
                            // 显示时间
                            LOG_INFO("RTC Time: %02d:%02d:%02d", 
                                     current_time.hours, current_time.minutes, current_time.seconds);
                            segment_display_RTC_time(current_time.hours, current_time.minutes, current_time.seconds, colon_visible);
                            break;
                            
                        case RTC_PAGE_DATE:
                            // 显示日期和星期
                            LOG_INFO("RTC Date: %02d/%02d Weekday: %d", 
                                     current_time.month, current_time.date, current_time.weekday);
                            segment_display_date(current_time.month, current_time.date, current_time.weekday);
                            break;
                            
                        case RTC_PAGE_YEAR:
                            // 显示年份
                            LOG_INFO("RTC Year: 20%02d", current_time.year);
                            segment_display_year(current_time.year);
                            break;
                            
                        default:
                            // 默认显示时间
                            segment_display_RTC_time(current_time.hours, current_time.minutes, current_time.seconds, colon_visible);
                            break;
                        }
                    }
                    LedHandleRegister(SYSTEM_NORMAL);
                    break;
                case SYSTEM_ALARM1_MODE:
                    // 处理闹钟1
                    alarm_process();
                    break;
                case SYSTEM_ALARM2_MODE:
                    // 处理闹钟2
                    alarm_process();
                    break;
                case SYSTEM_COUNTDOWN_MODE:
                    down_time.status = countdown_get_status();
                    LedHandleRegister(SYSTEM_NORMAL);
                    break;
                default:
                    break;
                }
        }

        if (systemWakeupEvent & SYSTEM_WAKEUP_EVT_CHARGE)
        {
            systemWakeupEvent &= ~SYSTEM_WAKEUP_EVT_CHARGE;
            // 充电状态下，只显示充电状态
            ht1621b_clear_buffer();
            segment_display_charge_status();
        }

        {
            // 在主循环中处理倒计时设置模式
            if (down_time.status == TICK_STATUS_SETTING)
            {
                key_long_press_lcd(&down_time);
            }else if (down_time.status == TICK_STATUS_RUNNING)
            {
                // 更新倒计时时间（包含显示更新）
                ht1621b_clear_buffer();
                countdown_update(colon_visible);
            }

            if (alarms[0].time.status == TICK_STATUS_SETTING)
            {
                key_long_press_lcd(&alarms[0].time);
            }

            if (alarms[1].time.status == TICK_STATUS_SETTING)
            {
                key_long_press_lcd(&alarms[1].time);
            }
        }
           
        // 处理RTC模式下的旋转编码器翻页
        if (systemWorkMode == SYSTEM_RTC_MODE && rotary_evt != ROTARY_EVENT_NONE)
        {
            switch (rotary_evt)
            {
            case ROTARY_EVENT_CLOCKWISE:
                // 顺时针旋转：切换到下一个页面
                rtc_current_page = (rtc_current_page + 1) % RTC_PAGE_COUNT;
                rtc_page_changed = true;
                LOG_INFO("Rotary clockwise - Switching to page %d", rtc_current_page);
                break;

            case ROTARY_EVENT_COUNTERCLOCKWISE:
                // 逆时针旋转：切换到上一个页面
                if (rtc_current_page == 0)
                {
                    rtc_current_page = RTC_PAGE_COUNT - 1;
                }
                else
                {
                    rtc_current_page = rtc_current_page - 1;
                }
                rtc_page_changed = true;
                LOG_INFO("Rotary counterclockwise - Switching to page %d", rtc_current_page);
                break;

            case ROTARY_EVENT_BUTTON_PRESSED:
                // 短按按钮：返回到时间页面
                rtc_current_page = RTC_PAGE_TIME;
                rtc_page_changed = true;
                LOG_INFO("Rotary button pressed - Returning to time page");
                break;

            default:
                break;
            }

            // 如果页面发生变化，立即更新显示
            if (rtc_page_changed)
            {
                rtc_page_changed = false;
                ht1621b_clear_buffer();

                switch (rtc_current_page)
                {
                case RTC_PAGE_TIME:
                    segment_display_RTC_time(current_time.hours, current_time.minutes, current_time.seconds, true);
                    break;

                case RTC_PAGE_DATE:
                    segment_display_date(current_time.month, current_time.date, current_time.weekday);
                    break;

                case RTC_PAGE_YEAR:
                    segment_display_year(current_time.year);
                    break;

                default:
                    segment_display_RTC_time(current_time.hours, current_time.minutes, current_time.seconds, true);
                    break;
                }
            }
            LOG_INFO("Rotary event processed: %d", rotary_evt);
            // 重置旋转编码器事件
            rotary_evt = ROTARY_EVENT_NONE;
        }

        if (tick_count >= 10000)
        {
            tick_count = 0;
        }

        // 处理按键事件
        key_handler_process();
        LedHandleProcess();
        LedSingleControl(MAIN_TASK_DELAY_MS, false);
        breathing_led_process();
        rotary_evt = rotary_encoder_process();
        ht1621b_display_update();
        // 延时以避免过度占用CPU
        vTaskDelay(pdMS_TO_TICKS(MAIN_TASK_DELAY_MS));
        }
}

int main()
{
    // 创建主任务（统一管理蜂鸣器、呼吸灯和按键操作）
    BaseType_t result = xTaskCreate(
        main_task_handler,
        MAIN_TASK_NAME,
        MAIN_TASK_STACK,
        NULL,
        MAIN_TASK_PRIO,
        &main_task_handle);

    if (result != pdPASS)
    {
        LOG_ERROR("Failed to create main control task");
        // 使用LED进行错误提示
        LedHandleRegister(SYSTEM_DEVICE_INIT_ERROR);
        return 1;
    }
    LOG_INFO("Main control task created successfully");

    // 启动FreeRTOS调度器
    vTaskStartScheduler();

    // 如果到达这里，说明调度器启动失败
    LOG_ERROR("Failed to start FreeRTOS scheduler");

    return 1;
}


void vApplicationTickHook(void) {
};

void vApplicationStackOverflowHook(TaskHandle_t Task, char *pcTaskName)
{
    panic("stack overflow (not the helpful kind) for %s\n", *pcTaskName);
}

void vApplicationMallocFailedHook(void)
{
    panic("Malloc Failed\n");
};

static void ds3231_int_handle(void)
{
    LOG_INFO("DS3231 interrupt received");
    RTC_1S_INT = true;
    systemWakeupEvent |= SYSTEM_WAKEUP_EVT_CLOCK;
        // 读取当前时间
    if (ds3231_get_time(&current_time))
    {      
        // 检查闹钟是否触发
        if (alarm_check_time(&current_time)) {
            LOG_INFO("Alarm triggered");
        }
    }
}
